<template>
    <div>
        <f7-block-title v-if="problem == null">暂无实测记录</f7-block-title>
        <f7-block v-else strong style="margin-top:0; margin-bottom:0; padding-top:3px; padding-bottom:3px;">
            <f7-row>
	            <f7-col>
	                <f7-badge :color="statusColor">{{problem.status}}</f7-badge>
	            </f7-col>
	            <f7-col></f7-col>
	        </f7-row>
	        <f7-row>
	            <f7-col width="30">标段</f7-col>
	            <f7-col width="70">
	               {{$store.state.global.bidSectionMap[$store.state.global.buildingMap[problem.building_id].bid_section_id].bid_section_name}}
	            </f7-col>
	        </f7-row>
	        <f7-row>
	            <f7-col width="30">检查项</f7-col>
	            <f7-col width="70">
	               {{$store.state.global.problemClassMap[$store.state.global.problemClassMap[problem.item_id].parent_problem_class_id].problem_class_name}}
                   &nbsp;-&nbsp;
                   {{$store.state.global.problemClassMap[problem.item_id].problem_class_name}}
	           </f7-col>
	        </f7-row>
	        <f7-row>
	            <f7-col width="30">实测点</f7-col>
	            <f7-col width="70">{{problem.measure_points}}</f7-col>
	        </f7-row>
	        <f7-row>
	            <f7-col width="30">合格率</f7-col>
	            <f7-col width="70">
	                {{qualificationRate}}%
	                &nbsp;&nbsp;&nbsp;&nbsp;
	                <f7-link href="#" @click="openHousePoint" v-if="hasDrawingFile">户型图</f7-link>
	            </f7-col>
	        </f7-row>
	        <f7-row>
	            <f7-col width="30">爆点数值</f7-col>
	            <f7-col width="70">{{displayProblemValues}}</f7-col>
	        </f7-row>
	        <f7-row>
	            <f7-col width="30">问题照片</f7-col>
	            <f7-col width="70">
	                <f7-list-item-cell>
	                    <img width="60" height="60" style="margin-right:5px;"
	                         v-for="(imageFile, i) in problem.image_file"
	                         :src="imageFile.url" @click="$refs.photoBrowser.open(i)">
	                    </img>
	                </f7-list-item-cell>
	                <f7-photo-browser :photos="problem.image_file"
	                    type="popup" ref="photoBrowser" back-link-text="关闭">
	                </f7-photo-browser>
	            </f7-col>
	        </f7-row>
	        <f7-row>
	            <f7-col width="30">检查人</f7-col>
	            <f7-col width="70">
	                {{$store.state.global.userMap[problem.regist_by].realname}}<br/>
	                {{formatDate(problem.regist_date)}}
	            </f7-col>
	        </f7-row>
            <f7-row>
                <f7-col width="30">整改人</f7-col>
                <f7-col width="70">
                    <span>{{problem.repair && $store.state.global.userMap[problem.repair].realname}}</span>
                </f7-col>
            </f7-row>
	        <f7-row>
	            <f7-col width="30">抄送人</f7-col>
	            <f7-col width="70">
	                <f7-row v-for="(cc, i) in problem.ccs" :key="cc" v-if="i % 4 == 0">
	                    <f7-col v-for="j in 4" :key="problem.ccs[i + j - 1]">
	                        <span v-if="i + j - 1 < problem.ccs.length">
	                            {{$store.state.global.userMap[problem.ccs[i + j - 1]].realname}}
	                        </span>
	                    </f7-col>
	                </f7-row>
	            </f7-col>
	        </f7-row>
            <f7-row v-if="!isOvertime && hasPermission">
                <f7-col width="70"></f7-col>
                <f7-col width="30" style="align:right;">
                    <f7-button @click="problemModify">修改数值</f7-button>
                </f7-col>
            </f7-row>
            <!-- <f7-row v-if="problem.status == '已整改'">
                <f7-col width="70"></f7-col>
                <f7-col width="30" style="align:right;">
                    <f7-button @click="problemReinspect">问题复验</f7-button>
                </f7-col>
            </f7-row> -->
        </f7-block>
    </div>
</template>

<script>
import Common from "@/utils/Common.js";
import DateUtil from "@/utils/DateUtil.js";
import $ from 'jquery';
import events from 'events';
import store from '@/store';
import { getUser, setUser, clearUser } from '@/utils/auth';

export default {
    store: store,
    props: {
    	problem: {
    		type: Object
    	}
    },
    data: function() {
        return {
        	
        };
    },
    methods: {
    	openHousePoint: function() {
            var self = this;
            var router = this.$f7router.navigate('/HousePoint', {
                props: {
                    imageUrl: this.problem.drawing_file[0].url,
                    pointCount: this.problem.measure_points,
                    initialPoints: this.problem.problem_values,
                    hasPointValue: true,
                    editable: false
                }
            });
    	},
    	formatDate: function(date) {
            return DateUtil.dateToStr('yyyy-MM-dd HH:mm', date);
    	},
    	problemModify: function() {
    		var self = this;
    		self.$f7.preloader.show();
    		let sql = "\
                select t.*, case when p.repairs is null then '[]' else p.repairs end as repairs, \
                    h.id, h.house_name, f.floor_name, u.unit_name, b.building_name, b.bid_section_id \
                from tb_quality_measure_checkquality_problem t \
                left join ( \
                    select quality_measure_checkquality_problem_id, \
                        '[' || group_concat('\"' || repair || '\"') || ']' as repairs \
                    from tb_quality_measure_checkquality_repair \
                    where quality_measure_checkquality_problem_id = '" + self.problem.id + "' \
                    group by quality_measure_checkquality_problem_id \
                ) p \
                on t.id = p.quality_measure_checkquality_problem_id \
                left join tb_house h    on t.room_id = h.id \
                left join tb_floor f    on t.floor_id = f.id \
                left join tb_unit u     on t.unit_id = u.id \
                left join tb_building b on t.building_id = b.id \
                where t.id = '" + self.problem.id + "' \
            ";
            Common.executeSql(sql, []).then((result) => {
            	let rs = result.rs;
            	var row = rs.rows.item(0);
            	row.repairs = Common.strToJson(row.repairs);
                row.repair = row.repairs[0];
                row.drawing_file = Common.strToJson(row.drawing_file);
                if(row.drawing_file == null) {
                	row.drawing_file = [];
                }
                var qualityMeasureProblem = row;
                
                var url = '/QualityMeasureProblemModify';
                var router = self.$f7router.navigate(url, {
                	props: {
                		qualityMeasureProblem: qualityMeasureProblem
                	}
                });
                router.off('qualityMeasureModify');
                router.on('qualityMeasureModify', function(obj) {
                    var problemId = obj.problemId;
                    var value = obj.value;
                    self.$set(self.$store.state.global.modifyMap, problemId, value);
                });
                self.$f7.preloader.hide();
            }).catch(error => {
            	console.error(error);
                self.$f7.preloader.hide();
            });
            
    	},
    	problemReinspect: function() {
    		var self = this;
    		var problem = self.convertQualityMeasureProblem(self.problem);
    		var url = '/QualityMeasureProblemReinspect';
    		var router = this.$f7router.navigate(url, {
                props: {
                	checkQualityProblem: problem,
                	sourceIsUnprocessed: false
                }
            });
    		router.off('problemUpdate');
            router.on('problemUpdate', function(qualityMeasureProblem) {
            	var array = [];
            	array.push(qualityMeasureProblem);
            	let sql = 
        			"select quality_measure_checkquality_problem_id, update_time " +
        			"from tb_quality_measure_checkquality_problem t " +
        			"where item_id = '" + qualityMeasureProblem.itemId + "' ";
            	Common.executeSql(sql, []).then((result) => {
            		let localMap = {};
            		let problems = array;
                    for(var i = 0; i < rs.rows.length; i++) {
                        var row = rs.rows.item(i);
                        var item = {};
                        item.quality_measure_checkquality_problem_id = row['quality_measure_checkquality_problem_id'];
                        item.update_time = row['update_time'];
                        localMap[item.quality_measure_checkquality_problem_id] = item;
                    }
                    let elements = [];
                    for(var i = 0; i < problems.length; i++) {
                    	var element = problems[i];
                    	if(localMap[element.entityId] && localMap[element.entityId].update_time != element.updateTimestamp) {
                    		elements.push(element);
                    	}
                    }
                    let sql = 
                        "update tb_quality_measure_checkquality_problem set " +
                        "update_time = ?, batch_type = ?, drawing_file = ?, image_file = ?, measure_points = ?, " +
                        "problem_points = ?, problem_values = ?, regist_date = ?, remark = ?, repair_date = ?, " +
                        "repair_image_file = ?, repair_remark = ?, sent_back_date = ?, sent_back_image_file = ?, " +
                        "sent_back_remark = ?, sent_back_times = ?, small_image_file = ?, " +
                        "small_repair_image_file = ?, small_sent_back_image_file = ?, standard_min = ?, standard_max = ?, " +
                        "status = ?, building_id = ?, floor_id = ?, room_id = ?, item_id = ?, regist_by = ?, repair_by = ?, " +
                        "unit_id = ?, app_permission = ?, ccs = ? " +
                        "where quality_measure_checkquality_problem_id = ?";
                    let batchSql = [];
                    for(var i = 0; i < elements.length; i++) {
                		let element = elements[i];
                		let values = [
                			element.updateTimestamp,
                			element.batchType,
                			element.drawingFile,
                			element.imageFile,
                			element.measurePoints,
                			element.problemPoints,
                			element.problemValues,
                			element.registTimestamp,
                			element.remark,
                			element.repairTimestamp,
                			element.repairImageFile,
                			element.repairRemark,
                			element.sentBackTimestamp,
                			element.sentBackImageFile,
                			element.sentBackRemark,
                			element.sentBackTimes,
                			element.smallImageFile,
                			element.smallRepairImageFile,
                			element.smallSentBackImageFile,
                			element.standardMin,
                			element.standardMax,
                			element.status,
                			element.buildingId,
                			element.floorId,
                			element.roomId,
                			element.itemId,
                			element.registBy,
                			element.repairBy,
                			element.unitId,
                			element.appPermission,
                			element.ccs,
                			element.entityId
                        ];
            			batchSql[i] = [sql, values];
                    }
                    return Common.sqlBatch(batchSql);
            	}).then(() => {
            		self.$emit('updateProblem', qualityMeasureProblem);
                	var backUrl = self.$f7router.history[self.$f7router.history.length - 3];
                	self.$f7router.back(backUrl ,{force: true});
            	}).catch(error => {
                	console.error(error);
            	});
            	
            	/* var emitter = new events.EventEmitter();
                emitter.once('updateQualityMeasureCheckQualityProblemsByItemId', function() {
                	self.$emit('updateProblem', qualityMeasureProblem);
                	var backUrl = self.$f7router.history[self.$f7router.history.length - 3];
                	self.$f7router.back(backUrl ,{force: true});
                });
				window.updateQualityMeasureCheckQualityProblemsByItemId(array, qualityMeasureProblem.itemId, emitter); */
            });
    	},
    	convertQualityMeasureProblem: function(row) {
        	var problem = {};
        	problem.appPermission = row.app_permission;
        	problem.batchType = row.batch_type;
        	problem.buildingId = row.building_id;
        	problem.buildingName = this.$store.state.global.buildingMap[row.building_id].building_name;
        	problem.ccs = row.ccs;
        	problem.drawingFile = row.drawing_file;
        	problem.floorId = row.floor_id;
        	problem.floorName = this.$store.state.global.floorMap[row.floor_id].floor_name;
        	problem.imageFile = row.image_file;
        	problem.problemClassId = row.item_id;
        	problem.measurePoints = row.measure_points;
        	problem.problemPoints = row.problem_points;
        	problem.problemValues = row.problem_values;
        	problem.qualityMeasureCheckqualityProblemId = row.quality_measure_checkquality_problem_id;
        	problem.registBy = row.regist_by;
        	problem.registDate = row.regist_date;
        	problem.remark = row.remark;
        	problem.repairBy = row.repair_by;
        	problem.repairDate = row.repair_date;
        	problem.repairImageFile = row.repair_image_file;
        	problem.repairRemark = row.repair_remark;
        	problem.roomId = row.room_id;
        	problem.roomName = this.$store.state.global.houseMap[row.room_id].house_name;
        	problem.sentBackDate = row.sent_back_date;
        	problem.sentBackImageFile = row.sent_back_image_file;
        	problem.sentBackRemark = row.sent_back_remark;
        	problem.sentBackTimes = row.sent_back_times;
        	problem.smallImageFile = row.small_image_file;
        	problem.smallRepairImageFile = row.small_repair_image_file;
        	problem.smallSentBackImageFile = row.small_sent_back_image_file;
        	problem.standardMax = row.standard_max;
        	problem.standardMin = row.standard_min;
        	problem.status = row.status;
        	problem.tid = row.tid;
        	problem.unitId = row.unit_id;
        	problem.unitName = this.$store.state.global.unitMap[row.unit_id].unit_name;
        	problem.updateTime = row.update_time;
        	problem.bidSectionId = this.$store.state.global.buildingMap[row.building_id].bid_section_id;
        	problem.repair = row.repair;
        	return problem;
        },
    },
    computed: {
    	statusColor: function() {
            switch(this.problem.status) {
	            case '检查完毕':
	                return 'green';
	            case '待整改':
	                return 'red';
	            case '已整改':
	                return 'orange';
	        }
	        return 'gray';
    	},
        qualificationRate: function() {
            if(this.problem.measure_points == 0) {
                return 0;
            }
            var rate = 1 - this.problem.problem_values.length / this.problem.measure_points;
            return (rate * 100).toFixed(1);
        },
        displayProblemValues: function() {
        	var values = this.problem.problem_values.map(function(problemValue) {
        		return problemValue.val;
        	});
        	return values.join(', ');
        },
        hasDrawingFile: function() {
        	if(this.problem.drawing_file != null && this.problem.drawing_file.length > 0) {
        		return true;
        	} else {
        		return false;
        	}
        },
        isOvertime: function() {
        	var registDay = 
        	    DateUtil.strFormatToDate('yyyy-MM-dd', DateUtil.dateToStr('yyyy-MM-dd', this.problem.regist_date));
        	var registTomrrow = DateUtil.dateAdd('d', 1, registDay);
        	return new Date() > registTomrrow;
        },
        hasPermission: function() {
        	var userPermission = this.$store.state.global.userMap[getUser().userId].app_permission;
        	var problemPermission = this.problem.app_permission;
        	return userPermission == problemPermission;
        },
        
    },
    watch: {
        
    },
    created: function() {
    	
    },
    mounted: function() {
    	
    }
}
</script>

<style scoped>

</style>